﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using FileDirUtils;
using iTunesExport.Parser;
using System.Collections.Specialized;
using iTunesUtil.Properties;
using System.IO;

namespace iTunesUtil
{
    public partial class CheckDlg : Form
    {
        #region vars       
        readonly TrackCollection tracks;
        readonly Dictionary<string, string> dictLowerCase = new Dictionary<string, string>();        
        StringCollection files;        
        #endregion

        #region properties
        public string Dir { get; set; }
        public List<string> MissingFiles { get; set; }
        public int NoCheckedFiles { get; set; }
        public int NoFilesInDir { get; set; }
        public bool Stop { get; set; }
        #endregion    

        public CheckDlg(TrackCollection tracks)
        {
            InitializeComponent();                        
            this.tracks = tracks;
            labelDir.Text = Dir = Settings.Default.CheckedDir;
            Text = string.Format("Directory: {0}", Dir);
            NoCheckedFiles = 0;
            MissingFiles = new List<string>();
            Stop = false;
        }

        public override sealed string Text
        {
            get { return base.Text; }
            set { base.Text = value; }
        }

        private void ShowProgress(int value, int max)
        {
            if (InvokeRequired)
            {
                Invoke(new Action<int,int>(ShowProgress), new object[] { value, max });                
                return;
            }
            progressBar1.Value = value;
            labelDir.Text = string.Format("{0}/{1} {2}%", value, max, (value * 100) / max);            
        }

        #region GetFiles
        private void GetFilesWorker()
        {
            foreach (Track currTrack in tracks.Tracks)
                dictLowerCase.Add(currTrack.Location.ToLower(), currTrack.Location);
            var fileGetter = new DirFilesGetter(true)
                                 {
                                     PosFileFilter = new FileFilterExtension(Settings.Default.FileFilter)
                                 };
            files = fileGetter.GetFilesFromDir(Dir);
       
            Invoke(new MethodInvoker(delegate {
                      Text = string.Format("{0} files in {1}", files.Count, Dir);
                      buttonStop.Visible = buttonStop.Enabled = true;
                      progressBar1.Style = ProgressBarStyle.Continuous;
                      progressBar1.Maximum = NoFilesInDir = files.Count;
                      new Action(CheckDirWorker).BeginInvoke(null, null);
                  }));
        }
        #endregion
        
        #region CheckDir
        public void CheckDirWorker()
        {                                                
            foreach (string file in files)
            {
                if (Stop)
                    break;                               
                if (!dictLowerCase.ContainsKey(file.ToLower()))
                {            
                    MissingFiles.Add(file.Substring(Dir.Length + 1));
                }
                if (++NoCheckedFiles % 10 == 0)
                    ShowProgress(NoCheckedFiles, NoFilesInDir);                    
            }
            Invoke(new MethodInvoker(delegate { DialogResult = DialogResult.OK;Close();}));
        }        
        #endregion

        #region button handler
        private void OnButtonStop(object sender, EventArgs e)
        {
            Stop = true;
        }
        private void OnButtonSelectDir(object sender, EventArgs e)
        {
            if (Program.BrowseForFolder(labelDir, "Select Directory", true))
            {
                Dir = labelDir.Text;
                Settings.Default.CheckedDir = Dir;
                Text = string.Format("Directory: {0}", Dir);
                Settings.Default.Save();
            }
        }                         
        private void OnButtonCheck(object sender, EventArgs e)
        {            
            if (!Directory.Exists(Dir))
            {
                MessageBox.Show("Directory '{0}' does not exist !", "Missing directory", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }            
            buttonDir.Visible = buttonDir.Enabled = false;
            buttonCheck.Visible = buttonCheck.Enabled = false;            
            progressBar1.Style = ProgressBarStyle.Marquee;
            labelDir.Text = string.Format("Getting files for directory '{0}'", Dir);
            new Action(GetFilesWorker).BeginInvoke(null, null);                                                         

        }        
        #endregion       
    }
}
